package game.module.qzmj.processor;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import game.common.PlayingRoleMsgProcessor;
import game.entity.PlayingRole;
import game.module.qzmj.bean.QzmjRoom;
import game.module.qzmj.logic.QzmjDataManager;
import game.session.SessionManager;
import lion.common.MsgCodeAnn;
import lion.netty4.message.MyRequestMessage;
import lion.netty4.message.RequestMessageRaw;
import lion.netty4.message.RequestProtoMessage;
import lua.LuaMessageLogin.S2ErrorCode;
import lua.LuaMessageQzmj.C2SQzmjSystemVoice;
import lua.LuaMessageQzmj.S2CQzmjSystemVoice;
import lua.LuaMessageQzmj.PushQzmjSystemVoice;

@MsgCodeAnn(msgcode = C2SQzmjSystemVoice.id, accessLimit = 500)
public class QzmjSystemVoiveProcessor extends PlayingRoleMsgProcessor{

	private static Logger logger = LoggerFactory.getLogger(QzmjSystemVoiveProcessor.class);
	@Override
	public void process(PlayingRole playingRole, RequestMessageRaw requestMessage) throws Exception {
		// TODO Auto-generated method stub
		C2SQzmjSystemVoice request = C2SQzmjSystemVoice.parse(requestMessage);
		byte voice_index = request.voice_index;
		int playerId = playingRole.getId();
		logger.info("qz mj hall voice msg play ={}",playerId);
		boolean isInRoom = QzmjDataManager.getInstance().isPlayerInRoom(playerId);
		if (!isInRoom) {
			S2ErrorCode respMsg = new S2ErrorCode(106);
			playingRole.writeAndFlush(respMsg.build(playingRole.alloc()));
			return;
		}
		// is room exist
		final QzmjRoom mjRoom = QzmjDataManager.getInstance().getMjRoomByPlayerId(playerId);
		if (mjRoom == null) {
			S2ErrorCode respMsg = new S2ErrorCode(106);
			playingRole.writeAndFlush(respMsg.build(playingRole.alloc()));
			return;
		}
		S2CQzmjSystemVoice respMsg = new S2CQzmjSystemVoice();
		playingRole.writeAndFlush(respMsg.build(playingRole.alloc()));//发送消息成功
		
		List<Integer> playerIdList = mjRoom.getPlayerList();
		PushQzmjSystemVoice pushMsg = new PushQzmjSystemVoice();
		
		pushMsg.play_index = (byte) playerIdList.indexOf(playerId);
		pushMsg.voice_index = voice_index;
		//推送
		for(Integer aplayer:playerIdList) {
			PlayingRole pr = SessionManager.getInstance().getPlayer(aplayer);
			if (pr != null && pr.isChannelActive()) {
				pr.writeAndFlush(pushMsg.build(pr.alloc()));
			}
		}
	}

	@Override
	public void processProto(PlayingRole playingRole, RequestProtoMessage request) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void processWebsocket(PlayingRole playingRole, MyRequestMessage request) throws Exception {
		// TODO Auto-generated method stub
		
	}

}
